<template>
  <Layout>
    <template #main-content>
      <!-- 聊天区域 -->
      <div class="mx-auto h-screen flex flex-col overflow-y-auto" ref="chatContainer">
        <!-- 顶部标题栏 -->
        <header
          class="sticky top-0 lg:w-1/2 md:w-[80%] md:min-w-[700px] transition-all duration-300 min-w-[380px]  mx-auto bg-white shadow-sm py-2 px-6">
          <h1 class="text-2xl font-bold text-gray-800 align-baseline">
            <SvgIcon name="aiBot" customCss="size-10 inline text-[#5d72f6] pb-1"></SvgIcon>
            <span> Kitten Bot</span>
          </h1>
        </header>

        <!-- 欢迎区域 -->
        <!-- <div class="bg-white mx-4 mt-6 rounded-lg shadow-sm p-6">
      <h2 class="text-xl font-semibold text-gray-800 mb-2">Welcome to AI Assistant</h2>
      <p class="text-gray-600">I'm here to help you with any questions you have. Start a conversation below!</p>
    </div> -->

        <!-- 聊天区域 max-w-3xl -->
        <main class="max-w-full min-w-[380px] lg:w-1/2 md:w-[80%] md:min-w-[700px] flex-1 p-4 chat-main mx-auto">

          <!-- 遍历聊天记录 -->
          <template v-for="(chat, index) in chatList" :key="index">
            <!-- 用户消息(右侧) -->
            <div v-if="chat.role === 'user'" class="flex justify-end mb-4">
              <div
                class="bg-blue-500 zcool text-white rounded-2xl rounded-tr-none px-4 py-3 max-w-xs md:max-w-md lg:max-w-lg">
                {{ chat.content }}
                <div class="text-xs text-blue-100 mt-1 text-right">2:30 PM</div>
              </div>
            </div>

            <!-- AI回复 -->
            <div v-if="chat.role === 'ai'" class="flex mb-4 mr-8 pr-8 lg:max-w-full">
              <!-- 头像 -->
              <div class="shrink-0 mr-3">
                <div class="w-8 h-8 rounded-full flex z-0 items-center justify-center ">
                  <SvgIcon name="aiBot" customCss="size-7 inline text-[#5d72f6] "></SvgIcon>
                </div>
              </div>
              <!-- 内容 -->
              <div class="bg-[#d6d1d18c] text-gray-800 rounded-2xl rounded-tl-none max-w-full px-4 py-3">
                <StreamMarkdownRender :content="chat.content" />
                <div class="text-xs text-gray-600 mt-1">2:31 PM</div>
              </div>
            </div>

          </template>


        </main>

        <!-- 分隔线 -->
        <!-- <div class="border-t border-gray-300 mx-4"></div> -->

        <!-- 底部信息区域
    <div class="px-4 py-2 text-sm text-gray-500 flex justify-between">
      <div>
        <span class="font-medium">Model:</span> GPT-4 Turbo
      </div>
      <div>
        <span class="font-medium">Tokens:</span> 0/4008
      </div>
    </div> -->

        <!-- 输入区域 -->
        <div
          class="sticky bottom-0 left-0 min-w-full lg:w-1/2 md:w-[80%] md:min-w-3xl sm:min-w-[640px] transition-all duration-300 mx-auto mb-7 bg-white">
          <ChatInputBox v-model="message"></ChatInputBox>
        </div>

      </div>
    </template>
  </Layout>
</template>

<script setup>
import { ref, onBeforeUnmount, nextTick } from 'vue'
import SvgIcon from '@/components/SvgIcon.vue'
import Layout from '@/layout/Layout.vue'
import ChatInputBox from '@/components/ChatInputBox.vue'
import StreamMarkdownRender from '@/components/StreamMarkdownRender.vue'


// 用户输出textarea 引用
const textareaRef = ref(null)

// ===================== 用戶会话 ========================
const chatList = ref([
  { role: 'ai', content: '我是Kitten Bot, 我可以帮你解答各种问题, 你有什么想问的吗?' }
])
const message = ref('')
let eventSource = null  // sse连接

// 发送消息
const sendMessage = async () => {
  // 校验发送的消息不能为空
  if (!message.value.trim()) return

  // 将用户发送的消息添加到 chatList 聊天列表中
  const userMessage = message.value.trim()
  chatList.value.push({ role: 'user', content: userMessage })

  // 点击发送按钮后，清空输入框
  message.value = ''
  // 将输入框的高度重置
  if (textareaRef.value) {
    textareaRef.value.style.height = 'auto'
  }

  // 添加一个占位的回复消息
  chatList.value.push({ role: 'ai', content: '' })

  try {
    // SSE
    eventSource = new EventSource(`http://localhost:9100/v6/ai/generateStream?message=${encodeURIComponent(userMessage)}`)
    // eventSource = new EventSource(`http://localhost:9100/v7/ai/generateStream?message=${encodeURIComponent(userMessage)}&lang=Java`)  // 结构化输出
    // eventSource = new EventSource(`http://localhost:9100/v14/ai/generateStream?message=${encodeURIComponent(userMessage)}&chatId=12`)   // mcp: 高德地图

    let responseText = ''
    // 处理消息事件
    eventSource.onmessage = (event) => {
      console.log('接收到数据: ', event.data)
      if (event.data) {
        let response = JSON.parse(event.data)
        responseText += response.v
        chatList.value[chatList.value.length - 1].content = responseText
        // 自动滚动
        scrollToBottom()
      }
    }

    eventSource.onerror = (error) => {
      // 通常 SSE 在完成传输后会触发一次 error 事件，这是正常的
      if (error.eventPhase === EventSource.CLOSED) {
        console.log('SSE正常关闭')
      } else {
        // 提示用户 “请求出错”
        chatList.value[chatList.value.length - 1].content = '抱歉，请求出错了，请稍后重试。'
      }

      // 关闭 SSE
      closeSSE()
      // 自动滚动
      scrollToBottom()
    }


  } catch (error) {
    console.error('发送消息错误: ', error)
    // 提示用户 “请求出错”
    chatList.value[chatList.value.length - 1].content = '抱歉，请求出错了，请稍后重试。'
    // 自动滚动
    scrollToBottom()
  }
}


// 自动滚动到底部
const chatContainer = ref(null)
const scrollToBottom = async () => {
  await nextTick() // 等待 Vue.js 完成 DOM 更新
  if (chatContainer.value) { // 若容器存在
    // 将容器的滚动条位置设置到最底部
    const container = chatContainer.value
    container.scrollTop = container.scrollHeight
  }
}


// 声明周期钩子
// 关闭 SSE 连接
const closeSSE = () => {
  if (eventSource) {
    eventSource.close()
    eventSource = null
  }
}

// 组件卸载时自动关闭连接
onBeforeUnmount(() => {
  closeSSE()
})

</script>

<style scoped>
/* 对话内容滚动条 */
.overflow-y-auto {
  scrollbar-color: rgba(45, 141, 197, 0.87) transparent;
  scrollbar-width: thin;
}
</style>